找传奇、传世资源到传世资源站!

C#_TCP&UDP_Demo

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

from clipboardfrom clipboardusing System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net.Sockets;using System.Threading;using System.Net;namespace SocketClient{ public partial class Form1 : Form { /// <summary> ///以本机作测试 /// </summary> private IPAddress serverIP = IPAddress.Parse("127.0.0.1"); /// <summary> ///完整终端地址 /// </summary> private IPEndPoint serverFullAddr; /// <summary> /// 连接套接字 /// </summary> private Socket sock; public Form1() { InitializeComponent(); btnClose.Enabled = false; } /// <summary> /// 连接服务器端 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnConn_Click(object sender, EventArgs e) { serverIP = IPAddress.Parse(tbxIP.Text); try { //设置IP和端口 serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text)); sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //指定本地主机地址和端口号 sock.Connect(serverFullAddr); btnConn.Enabled = false; lblError.Text = "连接服务器成功。。。。"; btnClose.Enabled = true; sock.Close(); } catch (Exception ee) { lblError.Text = "连接服务器失败。。。请仔细检查服务器是否开启" ee; } } /// <summary> /// 断开连接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnClose_Click(object sender, EventArgs e) { sock.Close(); btnConn.Enabled = true; } /// <summary> /// 发送 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSend_Click(object sender, EventArgs e) { //设置IP,端口 serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text)); sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //指定本地主机地址和端口号 sock.Connect(serverFullAddr); byte[] byteSend = System.Text.Encoding.Default.GetBytes(this.tbxMessage.Text); byte[] message = new byte[1024]; string mess = ""; int bytes = 0; try { //发送数据 sock.Send(byteSend); //接收数据 bytes = sock.Receive(message); mess = mess Encoding.Default.GetString(message, 0, bytes);//编码(当接收的字节大于1024的时候 这应该是循环接收,测试就没有那样写了) //do //{ // bytes = newSocket.Receive(message, message.Length, 0); // mess = mess Encoding.ASCII.GetString(message, 0, bytes); //} // while (bytes > 0); tbxMessage.Text = mess; } catch (Exception ex) { lblError.Text = "出现错误,请联系管理员" ex; } sock.Close(); } //清空消息 private void btnClean_Click(object sender, EventArgs e) { tbxMessage.Text = ""; } private void Form1_Load(object sender, EventArgs e) { } }}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复